package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper , SpecGroup> implements SpecGroupService {
    @Autowired
    SpecParamService specParamService;
    @Override
    public List<SpecGroup> querySpecGroupByCategoryId(Long cid) {
        //根据 分类ID查询 查询规格组 ，非主键查询。
        Map columnMap = new HashMap<>();
        columnMap.put("category_id", cid);
        return listByMap(columnMap);
    }

    /**
     * 新增规格组
     * @param specGroupDTO
     */
    @Override
    public void saveSpecGroup(SpecGroupDTO specGroupDTO) {
        SpecGroup specGroup = specGroupDTO.toEntity(SpecGroup.class);
        save(specGroup);
    }

    /**
     * 修改规格组
     * @param specGroupDTO
     */
    @Override
    public void updateSpecGroup(SpecGroupDTO specGroupDTO) {
        SpecGroup specGroup = specGroupDTO.toEntity(SpecGroup.class);
        updateById(specGroup);
    }
    /*
    * 根据分类id 查询规格组，及其组参数
    * */
    @Override
    public List<SpecGroupDTO> querySpecGroupDetailByCategoryId(Long cid) {
        //查询规格组
        List<SpecGroupDTO> specGroupDTOList = SpecGroupDTO.convertEntityList(query().eq("category_id",cid).list());
        // 考虑健壮性
        if (CollectionUtils.isEmpty(specGroupDTOList)){
            throw new LyException("该分类下的规格组不存在！",400);
        }
        for (SpecGroupDTO specGroupDTO : specGroupDTOList) {
            //根据组id 查询组内参数
            List<SpecParam> specParamList = specParamService.query().eq("group_id", specGroupDTO.getId()).list();
            //DTO属性赋值
            specGroupDTO.setParam(SpecParamDTO.convertEntityList(specParamList));
        }
        return specGroupDTOList;
    }
}
